#!/usr/env/bin python
# -*- coding:utf-8 -*-
import paramiko
import re
from concurrent.futures import ThreadPoolExecutor
import concurrent.futures

class HardOper:
    """
    define one dowith class
    """

    def __init__(self):
        hosts = self.gm.get_dic_from_type(1)
        print("hardoper hosts =", hosts)
        if(len(hosts) > 0):
            with concurrent.futures.ThreadPoolExecutor(max_workers=len(hosts)) as executor:
                futures = [executor.submit(self.get_device_uui_dic, hosts[key][0], hosts[key][1], hosts[key][2], hosts[key][3]) for key in hosts.keys()]
                for future in concurrent.futures.as_completed(futures):
                    future.add_done_callback(self.get_future_ret)


    def get_future_ret(self, future):
        ret = future.result()
        self.gm.device_uuid.update(ret)

    def get_device_uui_dic(self, host, port, username, password):
        uuid_dic = {}
        dic = {}
        cmd = 'nmcli -f DEVICE,UUID con show'
        try:
            ret = self.remote_exec_command(cmd, host, port, username, password)
            uuid_list = str(ret.get('stdout')).strip().split("\n")[1:]
            for uuid in uuid_list:
                ud_list = re.split(r'\s+', uuid)
                dic[ud_list[0]] = ud_list[1]
            uuid_dic[host] = dic
        except Exception as e:
            print("get_device_uui_dic error =", e)

        finally:
            return uuid_dic

    def remote_exec_command(self, command, host, port, username, password):
        try:
            # 创建SSH客户端
            ssh_client = paramiko.SSHClient()
            # 自动添加主机密钥
            # 使用 Paramiko 库进行 SSH 连接时，
            # 当连接到一个之前没有连接过的主机时，会出现一个警告，提示用户主机的密钥没有被认证。
            # 这时候可以使用 set_missing_host_key_policy() 方法来设置主机密钥的策略。
            # AutoAddPolicy() 会自动将新的主机密钥添加到本地的 known_hosts 文件中，
            # 以便下次连接时可以自动认证主机密钥，而不会再次出现警告。
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)

            # 连接远程服务器
            ssh_client.connect(host, port, username, password)

            # stdio 是输入， stdout 是输出，stderr错误输出
            stdio, stdout, stderr = ssh_client.exec_command(command)
            channel = stdout.channel
            status = channel.recv_exit_status()

            # stdout标准输出读取数据
            stdout = stdout.read().decode("utf-8")

            # stderr标准错误数据输出读取数据
            stderr = stderr.read().decode("utf-8")

            # 使用return 返回数据
            return {"stderr": stderr, "stdout": stdout, "status": status}

        except Exception as e:
            print(e)

        finally:
            try:
                ssh_client.close()
            except Exception as e:
                print(e)


if __name__ == "__main__":
    ip = '192.168.1.223'
    username = 'zk'
    password = 'zonkin123'
    port = 22
    ho = HardOper()
    ret = ho.get_device_uui_dic(ip, port, username, password)
    print(ret)
    print(ret[ip]['enp5s0'])

